<template>
	<view class="content">
		<mytabbar :current-page="1"></mytabbar>
		<!-- 收货地址 -->
		<view class="revice_address_row">
			<!-- 当收货地址 不存在 按钮显示  对象 空对象 bool类型也是true  -->
			<view class="address_btn" v-if="!address.userName">
				<button @click="handleChooseAddress" type="primary" plain>获取收货地址</button>
			</view>
			<!-- 当收货地址 存在 详细信息就显示 -->
			<view v-else class="user_info_row">
				<view class="user_info">
					<view>{{address.userName}}</view>
					<view>{{address.all}}</view>
				</view>
				<view class="user_phone">{{address.telNumber}}</view>
			</view>
		</view>

		<!-- 购物车内容 -->
		<view class="cart_content">
			<view class="cart_title">
				<view>我的购物车</view>
				<view @click="deleteChecked">移除</view>
			</view>
			<view class="cart_main">
				<!-- 当cart数组 长度不为0 显示 商品信息 -->
				<block v-if="cart.length">
					<view class="cart_item" v-for="item in cart" :key="item.saleBookId">
						<!-- 复选框 -->
						<view class="cart_chk_wrap">
							<checkbox-group :data-id="item.saleBookId" @click="handeItemChange">
								<checkbox :checked="item.checked"></checkbox>
							</checkbox-group>
						</view>
						<!-- 商品图片 -->
						<view class="cart_img_wrap">
							<image mode="aspectFit" :src="ImgUrl+item.bookImage">
							</image>
						</view>
						<!-- 商品信息 -->
						<view class="cart_info_wrap">
							<view class="goods_name">{{item.bookName}}</view>
							<view class="goods_price_wrap">
								<view class="goods_price">￥{{item.price}}</view>
								<view class="cart_num_tool">
									<view @click="handleItemNumEdit" :data-id="item.id" :data-operation="-1"
										class="num_edit">-</view>
								</view>
							</view>
						</view>
					</view>

				</block>
				<block v-else>
					<!-- <image class="immg" :wx-if="ImgUrl" mode="aspectFit" :src="ImgUrl+'123456789'">
					</image> -->
					<u-empty mode="car" icon="http://cdn.uviewui.com/uview/empty/car.png" width="300" height="300">
					</u-empty>
				</block>
			</view>
		</view>

		<!-- 底部工具栏 -->
		<view class="footer_tool">
			<!-- 全选 -->
			<view class="all_chk_wrap">
				<checkbox-group @change="handleItemAllCheck">
					<checkbox :checked="allChecked">全选</checkbox>
				</checkbox-group>
			</view>
			<!-- 总价格 -->
			<view class="total_price_wrap">
				<view class="total_price">
					合计: <text class="total_price_text">￥{{totalPrice.toFixed(2)}}</text>
				</view>
			</view>
			<!-- 结算 -->
			<view class="order_pay_wrap" @click="handlePay">
				结算({{totalNum}})
			</view>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				address: {},
				cart: [],
				allChecked: false,
				totalPrice: 0,
				totalNum: 0,
				ImgUrl: '',
				BaseUrl: '',
				token: ''
			}
		},
		onLoad() {
			this.ImgUrl = getApp().globalData.ImgUrl
			this.BaseUrl = getApp().globalData.BaseUrl
			this.token = uni.getStorageSync('token');
		},
		onShow() {
			this.init();
			this.allChecked = false
			this.totalPrice = 0
			this.totalNum = 0
		},
		onShareTimeline() {
			let title = '念旧书-校园闲置书籍跳蚤市场'
			return {
				title: title,
				path: 'pages/index/index',
				imageUrl: '../../static/logo.png'
			}
		},
		onShareAppMessage: function(e) {
			let title = '念旧书-校园闲置书籍跳蚤市场'
			return {
				title: title,
				path: 'pages/index/index',
				imageUrl: '../../static/logo.png'
			}
		},
		methods: {
			init() {
				let userinfo = uni.getStorageSync('userinfo')
				let userid = JSON.stringify(userinfo.id)
				uni.request({
					url: this.BaseUrl + '/cart/userCart',
					header: {
						'Content-Type': 'application/json',
						'token': this.token
					},
					data: {
						userId: userid
					},
					success: (res) => {
						this.cart = res.data.data
						if(this.cart.length!=0){
							this.cart.forEach(item=>{
								this.$set(item,"checked",false)
							})
						}
					}
				})
				const address = uni.getStorageSync("address");
				// 1 获取缓存中的购物车数据
				this.address = address
			},
			async handleChooseAddress() {
				try {
					// 1 获取 权限状态
					const res1 = await uni.getSetting();
					const scopeAddress = res1[1].authSetting["scope.address"];
					// 2 判断 权限状态
					if (scopeAddress === false) {
						await uni.openSetting();
					}
					// 4 调用获取收货地址的 api
					let addresss = await uni.chooseAddress();
					// console.log(addresss[1])
					let address = addresss[1]
					address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo;

					// 5 存入到缓存中
					uni.setStorageSync("address", address);

				} catch (error) {
					// console.log(error);
				}
			},
			// 商品的选中
			handeItemChange(e) {
				// 1 获取被修改的商品的id
				const goods_id = e.currentTarget.dataset.id;
				// 2 获取购物车数组 
				let {
					cart
				} = this;
				// 3 找到被修改的商品对象
				let index = cart.findIndex(v => v.saleBookId === goods_id);
				// 4 选中状态取反
				cart[index].checked = !cart[index].checked;

				this.setCart(cart);

			},
			// 设置购物车状态同时 重新计算 底部工具栏的数据 全选 总价格 购买的数量
			setCart(cart) {
				let allChecked = true;
				// 1 总价格 总数量
				let totalPrice = 0;
				let totalNum = 0;
				cart.forEach(v => {
					if (v.checked) {
						totalPrice += v.price;
						totalNum += 1;
					} else {
						allChecked = false;
					}
				})
				// 判断数组是否为空
				allChecked = cart.length != 0 ? allChecked : false;
				this.cart = cart
				this.totalPrice = totalPrice
				this.totalNum = totalNum
				this.allChecked = allChecked
				uni.setStorageSync("cart", cart);
			},
			// 商品全选功能
			handleItemAllCheck() {
				// 1 获取data中的数据
				let {
					cart,
					allChecked
				} = this;
				// 2 修改值
				allChecked = !allChecked;
				// 3 循环修改cart数组 中的商品选中状态
				cart.forEach(v => v.checked = allChecked);
				// 4 把修改后的值 填充回data或者缓存中
				this.setCart(cart);
			},
			deleteChecked() {
				let {
					cart,
				} = this;
				let len = Math.ceil(cart.length / 2)
				for (let i = 0; i <= len; i++) {
					this.deleteInit()
				}
			},
			deleteInit() {
				let {
					cart,
					token
				} = this;
				cart.forEach((v, i) => {
					if (v.checked === true) {
						cart.splice(i, 1);
						this.setCart(cart);
						uni.request({
							url: this.BaseUrl + '/cart/cancel',
							method: "POST",
							header: {
								'Content-Type': 'application/json',
								'token': token
							},
							data: {
								id: v.id
							},
							success: (res) => {
								// console.log(res)
							}
						})
					}
				});
			},
			// 商品数量的编辑功能
			handleItemNumEdit(e) {
				// 1 获取传递过来的参数 
				// console.log(e)
				const {
					operation,
					id
				} = e.currentTarget.dataset;
				// 2 获取购物车数组
				let {
					cart,
					token
				} = this;
				// 3 找到需要修改的商品的索引
				const index = cart.findIndex(v => v.id === id);
				// 4 判断是否要执行删除
				if (operation === -1) {
					// 4.1 弹窗提示
					uni.showModal({
						content: "您是否要删除？",
						success: (res) => {
							if (res.confirm) {
								cart.splice(index, 1);
								this.setCart(cart);
								uni.request({
									url: this.BaseUrl + '/cart/cancel',
									method: "POST",
									header: {
										'Content-Type': 'application/json',
										'token': token
									},
									data: {
										id: id
									},
									success: (res) => {
										// console.log(res)
									}
								})
							}
						},
						fail(res) {
							// console.log(this)
						}
					});


				}
			},

			// 点击 结算 
			async handlePay() {
				// 1 判断收货地址
				const {
					address,
					totalNum,
					cart
				} = this;
				let token = uni.getStorageSync('token');
				if (!address.userName) {
					await uni.showToast({
						title: "您还未选择收货地址",
						icon: "error"
					});
					return;
				}
				// 2 判断用户有没有选购商品
				if (totalNum === 0) {
					await uni.showToast({
						title: "您还未选购商品",
						icon: "error"
					});
					return;
				}
				let selectedBook = []
				cart.forEach(v => {
					if (v.checked === true) {
						selectedBook.push(v.saleBookId)
					}
				})
				let Address = {}
				Address.all = address.all
				Address.username = address.userName
				Address.telNumber = address.telNumber
				uni.request({
					url: this.BaseUrl + '/order/create',
					method: "POST",
					header: {
						'Content-Type': 'application/json',
						'token': token
					},
					data: {
						"address": JSON.stringify(Address),
						"saleBookIds": selectedBook
					},
					success: (res) => {
						// console.log(res)
						this.init()
						uni.navigateTo({
							url: '/pages/orders/orders'
						});
					},
				})

				// 3 跳转到 支付页面
				uni.navigateTo({
					url: '/pages/pay/index'
				});

			}
		}
	}
</script>

<style scoped>
	.content {
		height: 100%;
		padding-bottom: 90rpx;
	}

	.revice_address_row .address_btn {
		padding: 20rpx;
	}

	.revice_address_row .address_btn button {
		width: 60%;
	}

	.revice_address_row .user_info_row {
		display: flex;
		padding: 20rpx;
	}

	.revice_address_row .user_info_row .user_info {
		flex: 5;
	}

	.revice_address_row .user_info_row .user_phone {
		flex: 3;
		text-align: right;
	}

	.cart_content .cart_title {
		padding: 15rpx;
		font-size: 36rpx;
		border-top: 1rpx solid #888;
		border-bottom: 1rpx solid #888;
		display: flex;
	}

	.cart_content .cart_title view:nth-child(2) {
		position: relative;
		left: 450upx;
		top: 5upx;
		font-size: 28upx;
		color: #888;
	}

	.cart_content .cart_main {
		margin-bottom: 190upx;
	}

	.cart_content .cart_main .cart_item {
		display: flex;
		padding: 10rpx;
		border-bottom: 1rpx solid #ccc;
		height: 250upx;
	}

	.cart_content .cart_main .cart_item .cart_chk_wrap {
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.cart_content .cart_main .cart_item .cart_img_wrap {
		flex: 2;
		display: flex;
		justify-content: center;
		align-items: center;
		overflow: hidden;
	}

	.cart_content .cart_main .cart_item .cart_img_wrap image {
		width: 80%;
	}

	.cart_content .cart_main .cart_item .cart_info_wrap {
		flex: 4;
		display: flex;
		flex-direction: column;
		justify-content: space-around;
	}

	.cart_content .cart_main .cart_item .cart_info_wrap .goods_name {
		display: -webkit-box;
		overflow: hidden;
		font-size: 36upx;
		font-weight: bold;
		margin-left: 10upx;
		color: #666;
	}

	.cart_content .cart_main .cart_item .cart_info_wrap .goods_price_wrap {
		display: flex;
		justify-content: space-between;
	}

	.cart_content .cart_main .cart_item .cart_info_wrap .goods_price_wrap .goods_price {
		font-size: 34rpx;
		color: tomato;
		font-weight: bold;
	}

	.cart_content .cart_main .cart_item .cart_info_wrap .goods_price_wrap .cart_num_tool {
		display: flex;
	}

	.cart_content .cart_main .cart_item .cart_info_wrap .goods_price_wrap .cart_num_tool .num_edit {
		width: 55rpx;
		height: 55rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		border: 1rpx solid #ccc;
	}

	.cart_content .cart_main .cart_item .cart_info_wrap .goods_price_wrap .cart_num_tool .goods_num {
		width: 55rpx;
		height: 55rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.footer_tool {
		position: fixed;
		bottom: 110upx;
		left: 0;
		width: 100%;
		height: 90rpx;
		background-color: #fff;
		display: flex;
		border-top: 1rpx solid #ccc;
	}

	.footer_tool .all_chk_wrap {
		flex: 2;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.footer_tool .total_price_wrap {
		flex: 5;
		padding-right: 15rpx;
		text-align: right;
	}

	.footer_tool .total_price_wrap .total_price .total_price_text {
		color: var(--themeColor);
		font-size: 34rpx;
		font-weight: 600;
	}

	.footer_tool .order_pay_wrap {
		flex: 3;
		background-color: tomato;
		color: #fff;
		font-size: 32rpx;
		font-weight: 600;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.immg {
		position: relative;
		left: 50%;
		transform: translate(-50%);
	}
</style>
